library(tidyverse)
library(haven)
library(texreg)
library(margins)
library(broom)
library(prediction)
library(dotwhisker)

outputs_path <- "../../outputs/replication/"

source("functions_exp_models.R")

source("texreg_variable_list.R")

ex <- read_rds("../../data/replication/experiment_data_tidied.rds") 

controls_vec <- c("treatment_w21",
                  "male_w21",
                  "white_british_w21", 
                  "age_w21",
                  "class_w21",
                  "education_w21")

dvars <- tibble(variables = "uk_covid_performance_w21_num",
                neat_names = "Overall") %>%
  add_row(variables = "covid_overall_gov_fault_w21",
          neat_names = "Overall resp") %>%
  add_row(variables = "death_toll_gov_fault_w21",
          neat_names = "Death toll") %>%
  add_row(variables = "vaccine_gov_fault_w21",
          neat_names = "Vaccine") %>%
  add_row(variables = "retro_handle_w21_num",
          neat_names = "Retro handle") %>%
  add_row(variables = "retro_handle_change_w21",
          neat_names = "Change in retro handle") 

robust_party <- map(dvars$variables, 
                    data = (ex %>%
                      filter(rm_for_party != 1) %>%
                      filter(rm_for_vaccine_attitude != 1)),
                    weights = "wt_with_pol_att_w21",
                    interaction_term = "pol_attention_w21",
                    ols_treatment_interaction)

# defining function in file since might want different coef maps or 
# scale boxes for different models
custom_texreg <- function(list_of_models, ...){
  customised_reg <- generic_tidy_texreg(list_of_models,
    sideways = FALSE,
    custom.note = ("\\normalsize{%stars}"),
    custom.coef.map = texreg_variable_list,
    scalebox = 0.6,
    ...)

  return(customised_reg)
}

# get the right models based on choice defined at top of document
results_no_controls <- map(robust_party, function(x) x$no_controls)
results_with_controls <- map(robust_party, function(x) x$with_controls)

caption_suffix <- paste("Results from OLS regressions of all dependent",
                        "variables on treatment status interacted",
                        "with self-reported political attention")

custom_texreg(results_with_controls,
       custom.header = list("\\textit{Dependent variable:}" = 
                            1:(length(dvars$neat_names))),
       custom.model.names = dvars$neat_names,
       caption = paste0(caption_suffix, ", with demographic controls added"),
       label = "tab: pol_att_intx_controls",
       groups = list("Treatment: (ref = Control)" = 1:2,
                     "Age: (ref = Under 18)" = 8:10,
                     "Class: (ref = Higher Managerial)" = 11:15,
                     "Education: (ref = Undergrad or Higher)" = 16:19),
       file = paste0(outputs_path, "pol_att_with_controls.tex"))

